package com.gitee.hermer.engine.jars.starter.web.api;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.EngineMappingRegistrationCache;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import com.gitee.hermer.boot.jee.commons.collection.CollectionUtils;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.engine.jars.app.sdk.EngineAppClassLoader;
import com.gitee.hermer.engine.jars.core.annotate.EngineAppRestDescribe;
import com.gitee.hermer.engine.jars.core.app.domain.EngineAppRestDescribeBean;
import com.gitee.hermer.engine.jars.core.domain.BaseInfo;

@RestController
@RequestMapping("api/execute-mapping")
public class EngineApiMappingController extends UtilsContext{

	@RequestMapping("list")
	public BaseInfo<EngineAppRestDescribeBean> list(){
		try{
			Map<RequestMappingInfo, HandlerMethod> lookups = EngineMappingRegistrationCache.getInstance().getMappingLookup();
			List<EngineAppRestDescribeBean> describeBeans = new CollectionUtils().newArrayList();
			for (RequestMappingInfo info: lookups.keySet()) {
				HandlerMethod method = lookups.get(info);
				EngineAppRestDescribe describe = AnnotatedElementUtils.getMergedAnnotation(method.getMethod(), EngineAppRestDescribe.class);
				if(describe != null && (method.getClassLoader() instanceof EngineAppClassLoader)){
					Set<String> urls = info.getPatternsCondition().getPatterns();
					for (String url : urls) {
						describeBeans.add(new EngineAppRestDescribeBean(((EngineAppClassLoader)method.getClassLoader()).getCacheKey(),
								url, info.getMethodsCondition().toString(), describe.describe()));
					}
				}
			}
			return new BaseInfo<EngineAppRestDescribeBean>("", describeBeans);
		}catch (Exception e) {
			error(e.getMessage(),e);
		}
		return new BaseInfo<EngineAppRestDescribeBean>("", false);
	}

}
